<template>
  <McLayout class="smart-shopping-container">
    <!-- MateChat 头部组件 -->
    <McHeader 
      :title="'智能导购助手'" 
      :logoImg="'https://matechat.gitcode.com/logo.svg'"
    >
      <template #operationArea>
        <div class="operations">
          <i class="icon-shopping-cart"></i>
          <span>购物车</span>
        </div>
      </template>
    </McHeader>
    
    <!-- 对话内容区域 --> 
    <McLayoutContent class="chat-content" virtual-scroll>
      <!-- 欢迎页面 -->
      <McIntroduction 
        v-if="showWelcome"
        :logoImg="'https://matechat.gitcode.com/logo2x.svg'"
        :title="'智能导购助手'"
        :subTitle="'您好！我是您的专属购物顾问'"
        :description="welcomeDescription"
      />
      
      <!-- 对话消息区域 -->
      <template v-else>
        <div 
          v-for="(msg, idx) in messages" 
          :key="msg.id"
          class="message-wrapper"
        >
          <!-- 用户消息 -->
          <McBubble 
            v-if="msg.from === 'user'"
            :content="msg.content"
            :align="'right'"
            :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg' }"
          />
          
          <!-- AI消息 -->
          <McBubble 
            v-else
            :content="msg.content"
            :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/logo.svg' }"
            :loading="msg.loading"
          >
            <!-- 商品卡片插槽 -->
            <template v-if="msg.type === 'product' && msg.productData">
              <ProductCard 
                :data="msg.productData"
                @buy="handleBuyProduct"
              />
            </template>
          </McBubble>
        </div>
      </template>
    </McLayoutContent>
    
    <!-- 快捷操作区域 -->
    <div class="shortcut" v-if="!showWelcome">
      <McPrompt 
        :list="quickPrompts"
        :direction="'horizontal'"
        style="flex: 1"
        @itemClick="handleQuickPrompt"
      />
      <d-button 
        icon="add" 
        shape="circle" 
        title="新建对话" 
        size="md" 
        @click="newConversation" 
      />
    </div>
    
    <!-- 输入区域 -->
    <McLayoutSender>
      <McInput 
        :value="inputValue" 
        :maxLength="2000" 
        @change="handleInputChange"
        @submit="handleSubmit"
      >
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span v-for="(item, index) in inputFootIcons" :key="index">
                <i :class="item.icon"></i>
              </span>
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength">
                {{ inputValue.length }} / 2000
              </span>
            </div>
            <div class="input-foot-right">
              <d-button 
                icon="op-clearup" 
                shape="round" 
                :disabled="!inputValue" 
                @click="inputValue = ''"
              >
                <span class="demo-button-content">清空输入</span>
              </d-button>
            </div>
          </div>
        </template>
      </McInput>
    </McLayoutSender>
  </McLayout>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Button } from 'vue-devui/button'
import ProductCard from './ProductCard.vue'
import type { Message, ProductData } from '../types'

// 欢迎描述
const welcomeDescription = [
  'MateChat 可以为您推荐适合的商品、比较不同产品、提供优惠信息等。',
  '作为智能导购助手，我会根据您的需求提供个性化的购物建议。'
]

// 快捷提示
const quickPrompts = [
  {
    value: 'headphone',
    iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
    label: '推荐降噪耳机'
  },
  {
    value: 'gift',
    iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
    label: '程序员男友礼物'
  },
  {
    value: 'laptop',
    iconConfig: { name: 'icon-priority', color: '#3ac295' },
    label: '轻薄笔记本推荐'
  }
]

// 输入框底部图标
const inputFootIcons = [
  { icon: 'icon-at', text: '智能体' },
  { icon: 'icon-standard', text: '词库' },
  { icon: 'icon-add', text: '附件' }
]

// 状态管理
const showWelcome = ref(true)
const inputValue = ref('')
const messages = ref<Message[]>([])

// 模拟商品数据
const mockProducts: Record<string, ProductData> = {
  headphone: {
    id: '1',
    name: '华为FreeBuds Pro 3',
    price: 1499,
    specs: '麒麟A2芯片，智能动态降噪，超强续航',
    discount: 200
  },
  gift: {
    id: '2',
    name: '程序员男友专属机械键盘',
    price: 899,
    specs: 'Cherry轴体，RGB背光，全键无冲',
    image: 'https://example.com/keyboard.jpg'
  },
  laptop: {
    id: '3',
    name: '华为MateBook X Pro',
    price: 8999,
    specs: '13代酷睿，3K触控屏，超薄设计',
    discount: 500
  }
}

// 处理快速提示点击
const handleQuickPrompt = (event: any) => {
  inputValue.value = event.label
  handleSubmit()
}

// 处理输入变化
const handleInputChange = (value: string) => {
  inputValue.value = value
}

// 处理提交
const handleSubmit = () => {
  if (!inputValue.value.trim()) return
  
  const userMessage: Message = {
    id: Date.now().toString(),
    from: 'user',
    content: inputValue.value,
    timestamp: Date.now()
  }
  
  messages.value.push(userMessage)
  showWelcome.value = false
  
  // 模拟AI回复
  simulateAIResponse(inputValue.value)
  
  inputValue.value = ''
}

// 模拟AI回复
const simulateAIResponse = async (userInput: string) => {
  const loadingMessage: Message = {
    id: `loading-${Date.now()}`,
    from: 'model',
    content: '',
    loading: true,
    timestamp: Date.now()
  }
  
  messages.value.push(loadingMessage)
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 移除loading消息
  messages.value = messages.value.filter(msg => msg.id !== loadingMessage.id)
  
  let responseContent = ''
  let productData: ProductData | undefined
  
  // 根据用户输入生成回复
  if (userInput.includes('耳机') || userInput.includes('降噪')) {
    responseContent = '根据您的需求，我为您推荐这款降噪耳机：'
    productData = mockProducts.headphone
  } else if (userInput.includes('礼物') || userInput.includes('男友')) {
    responseContent = '送给程序员男友的礼物，这款机械键盘非常合适：'
    productData = mockProducts.gift
  } else if (userInput.includes('笔记本') || userInput.includes('电脑')) {
    responseContent = '为您推荐这款轻薄笔记本：'
    productData = mockProducts.laptop
  } else {
    responseContent = `感谢您的咨询！关于"${userInput}"，我理解您需要相关的产品推荐。我们的智能导购系统可以为您提供个性化的购物建议。`
  }
  
  const aiMessage: Message = {
    id: Date.now().toString(),
    from: 'model',
    content: responseContent,
    type: productData ? 'product' : 'text',
    productData,
    timestamp: Date.now()
  }
  
  messages.value.push(aiMessage)
}

// 处理购买商品
const handleBuyProduct = (product: ProductData) => {
  const message: Message = {
    id: Date.now().toString(),
    from: 'user',
    content: `立即购买：${product.name}`,
    timestamp: Date.now()
  }
  
  messages.value.push(message)
  
  // 模拟购买确认
  setTimeout(() => {
    const confirmMessage: Message = {
      id: Date.now().toString(),
      from: 'model',
      content: `已为您将"${product.name}"加入购物车！当前享受优惠价 ¥${product.price}。`,
      timestamp: Date.now()
    }
    messages.value.push(confirmMessage)
  }, 500)
}

// 新建对话
const newConversation = () => {
  showWelcome.value = true
  messages.value = []
}
</script>

<style scoped>
.smart-shopping-container {
  width: 1000px;
  margin: 20px auto;
  height: calc(100vh - 82px);
  padding: 20px;
  gap: 8px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 16px;
}

.chat-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow: auto;
}

.message-wrapper {
  margin: 8px 0;
}

.shortcut {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 12px 0;
}

.operations {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;
}

.input-foot-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-foot-left span {
  font-size: 14px;
  line-height: 18px;
  color: #252b3a;
  cursor: pointer;
}

.input-foot-dividing-line {
  width: 1px;
  height: 14px;
  background-color: #d7d8da;
}

.input-foot-maxlength {
  font-size: 14px;
  color: #71757f;
}

.input-foot-right .demo-button-content {
  font-size: 14px;
}

.input-foot-right > *:not(:first-child) {
  margin-left: 8px;
}
</style>